<?php

namespace App\Http\Common;

use Illuminate\Support\Facades\Log;
use App\Models\AccessToken;
use App\Models\WxUser;

class Consumer
{
//    protected $appid = "wx44020a0c14f0a6e8";//AppID(蓝月亮洗涤科技)
    public $appid = "wx17def53be3732dcd";//AppID(月亮之家)
//    protected $secret = "ae3ee4bb340203196d3d2fdda5913278";//AppSecret(蓝月亮洗涤科技)
    public $secret = "8c9bd3493a55891f344e7eebfab9ee39";//AppSecret(月亮之家)

    //微信登录token过期时间(天)
    public $token_day = 3;

    /**
     * 获取微信Access_Token
     *
     * @return string $access_token
     */
    public function getWxAccessToken(){
        $token = AccessToken::where('type', 1)->select('access_token', 'expire_time')->first();
        if($token){
            $expire_time = $token['expire_time'];
            if($expire_time > time()){
                $access_token = $token['access_token'];

                AccessToken::where('type', 1)->update(array('update_time' => time()));
            }else{
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret;
                $res = curl_get($url);
                $res = json_decode($res,true);
                $access_token = $res['access_token'];

                $new_expire_time = time() + 7;
                AccessToken::where('type', 1)->update(array('access_token' => $access_token,'expire_time' => $new_expire_time,'update_time' => time()));
            }
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret;
            $res = curl_get($url);
            $res = json_decode($res,true);
            $access_token = $res['access_token'];

            $expire_time = time() + 7;
            AccessToken::insert(array('access_token' => $access_token,'expire_time' => $expire_time,'update_time' => time(),'type' => 1));
        }
        return $access_token;
    }

    /**
     * 获取微信用户基本信息(已关注用户)
     *
     * @param string $openid 普通用户的标识，对当前公众号唯一
     * @return array $user_msg_list 用户信息数组
     */
    public function getWxUserInfo($openid){
        $access_token = $this->getWxAccessToken();
        //获取微信用户信息
        $get_user_info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user_msg_str = curl_get($get_user_info_url);
        $user_msg_list = json_decode($user_msg_str, true);

//        $unionid = $user_msg_list['unionid'];
//        if($unionid){
//            $WxUser = WxUser::where(array('unionid'=>$unionid))->select('id')->first();
//            if($WxUser){
//                //更新用户信息
//                WxUser::where(array('unionid'=>$unionid))->update(array('nickname' => $user_msg_list['nickname'],"sex" => $user_msg_list['sex'],'headimgurl' => $user_msg_list['headimgurl']));
//            }else{
//                //创建用户信息
//                WxUser::insert(array('unionid'=>$unionid,'openid' => $openid,'nickname' => $user_msg_list['nickname'],"sex" => $user_msg_list['sex'],'headimgurl' => $user_msg_list['headimgurl']));
//            }
//        }

        return $user_msg_list;
    }

    /**
     * 回复文本消息
     *
     * @param  string  $toUser      接收方帐号（收到的OpenID）
     * @param  string  $fromUser    开发者微信号
     * @param  int     $createTime  消息创建时间
     * @param  string  $content	    回复的消息内容（换行：在content中能够换行，微信客户端就支持换行显示）
     * @return string  $info        微信推送的数据（xml格式）
     */
    public function return_content($toUser,$fromUser,$createTime,$content){
        $template =
            "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Content><![CDATA[%s]]></Content>
             </xml>";
        $msgType  = 'text';
        $info = sprintf($template, $toUser, $fromUser, $createTime, $msgType, $content);
        echo $info;
    }

    /**
     * 验证微信用户token
     *
     * @param  string  $token  微信用户token
     */
    public function check_token($token){
        $de_res = array('msg'=>'token无效', 'error'=> 4002, 'data'=> '');
        $en_res = json_encode($de_res, 320);

        $Token = WxUser::where(array('token' => $token))->select('token_at')->first();
        if(!isset($Token)){
            exit($en_res);
        }else{
            $token_at = $Token['token_at'];
            $over_token_at = strtotime($token_at) + $this->token_day * 24 * 3600;
            if($over_token_at < time()){
                exit($en_res);
            }
        }
    }
}
